package com.eliza.room.db.dao

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import com.eliza.room.model.Student
import io.reactivex.annotations.SchedulerSupport


/*
* 指定表 版本 版本升级变化
* */
/*
* exportSchema ==》true 导出 数据信息文件
* 导出位置 模块下
* build.gradle-->  android
                        javaCompileOptions {
                            annotationProcessorOptions {
                                arguments =
* */
@Database(entities = [Student::class], version = 1, exportSchema = true)
abstract class StuRoomDatabase : RoomDatabase() {
    abstract val studentDao: StudentDao

    companion object {
        private const val DATABASE_NAME = "my_db.db"
        private var mInstance: StuRoomDatabase? = null

        //private MyDatabase(){}
        @Synchronized
        fun getInstance(context: Context): StuRoomDatabase {
            if (mInstance == null) {
                mInstance = Room.databaseBuilder(
                    context.applicationContext,
                    StuRoomDatabase::class.java,
                    DATABASE_NAME
                )
//                    .addMigrations(migration_1_2)
                    .build()
            }

            return mInstance as StuRoomDatabase
        }

        fun getInstance2(context: Context): StuRoomDatabase {
            synchronized(this) {
                if (mInstance == null) {
                    mInstance = Room.databaseBuilder(
                        context.applicationContext,
                        StuRoomDatabase::class.java,
                        DATABASE_NAME
                    ).addMigrations(migration_1_2, migration_2_3)
                        /**
                         * 出现异常不会报错，但会清空数据*/
                        .fallbackToDestructiveMigration()
                        .build()
                }
                return mInstance as StuRoomDatabase
            }
        }


        /**
         * 数据库 版本更新
         *
         * 1, 定义版本更替 变量 migration_1_2
         * 2,.addMigrations(migration_1_2)
         *    .build()
         * 3, model 实体类添加 对应属性
         * 4,修改注解版本 version：： @Database(entities = [Student::class], version = 1, exportSchema = false)
         * 执行顺序了：： 1==》3 ：{1-->3; 1-->2,2--3}
         * */
//         override fun migrate(database: SupportSQLiteDatabase) = migrateCallback(database)
        private var migration_1_2: Migration = Migration(1, 2) { database ->
            database.execSQL("Alter Table Student ADD COLUMN sex INTEGER NOT NULL default 1 ")
        }
        private var migration_2_3: Migration = Migration(2, 3) { database ->
            database.execSQL("Alter Table Student ADD COLUMN weight INTEGER NOT NULL DEFAUlT 0 ")
        }


    }
}
